﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using CMISForSharePoint.cmisTypes;
using CMISForSharePoint.Divers;
using CMISForSharePoint.cmisExceptions;
using CMISForSharePoint.cmisEnums;
using System.Text.RegularExpressions;



namespace CMISForSharePoint.cmisHelpers
{
    class CmisHelper
    {


        public static string[] CmisFilterParser(string filter)
        {
            string filterGrammar = @"^\s*[\*]\s*$|^(\s*\w+\s*)(,\s*\w+\s*)*$";
            Match match = Regex.Match(filter, filterGrammar);
            if (match.Success)
            {
                string[] response;
                if (match.Value != "*")
                {
                    response = match.Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < response.Length; i++)
                    {
                        response[i] = response[i].Trim();

                    }

                }
                else
                {
                    response = new string[] { "*" };
                }

                response=response.Distinct().ToArray();
                return response;
            }
            return null;
        }
        public static string[] OrderByClauseParser(string clause)
        {
            string grammar = @"^(\s*\w+\s+)(DESC|ASC)$";
            Match match = Regex.Match(clause, grammar, RegexOptions.IgnoreCase);
            string[] response = new string[0];
            if (match.Success)
            {
                response = new string[2];
                response[0] = match.Groups[1].Value.Trim();
                response[1] = match.Groups[2].Value.Trim();
            }
            return response;

        }
        public static cmisProperty[] CmisPropertyFilter( cmisProperty[] properties, string[] filter)
        {
            if (filter[0]!="*")
            {

                List<cmisProperty> response = new List<cmisProperty>();
                Dictionary<string, cmisProperty> dico = properties.ToDictionary(p => p.name);


                foreach (string item in filter)
                {
                    if (dico.Keys.Contains(item))
                    {
                        response.Add(dico[item]);
                    }

                }


                return response.ToArray();

            }
            else
            {
                return properties;
            }
        }



    }
}
